<template>
  <div >
    <el-cascader
      v-model="mutiOptionsValue"
      v-show="options.length>0"
      :options="options"
      :props="{ multiple: true }"
      collapse-tags
      clearable
      @change="selectchange"
    ></el-cascader>
    <el-col :xs="24" :sm="24" :lg="24">

      <div style="text-align: right; margin-bottom: 20px;">
        <el-button
          :loading="downloadLoading"
          class="filter-item"
          type="primary"
          icon="el-icon-download"
          @click="handleDownload"
        >
          Export
        </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
        element-loading-text="正在查询中。。。"
        :cell-class-name="addClass"
        @cell-click="cellDbClick"
        border
        auto-fit-column
        :header-cell-class-name="headerClassNmae"
      >
        <template v-for="(item,index) in head">
          <table-column
            v-if="Array.isArray(item)"
            :key="index"
            :index="index"
            :coloumn-header="item"
            :mapping-name="mappingName"></table-column>
          <el-table-column
            v-else
            :key="index"
            :label="mappingName[index]"
            :prop="index"
            auto-fit
            align="center"></el-table-column>
        </template>
      </el-table>
      <div style="text-align: right; margin-top: 20px;">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5,10, 20, 50, 100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-col>
  </div>
</template>

<script>
import TableColumn from './TableColumn'

export default {
  props: {
    gridTableHeader: {
      type: Object, default: () => {
      }
    },
    mappingName: {
      type: Object, default: () => {
      }
    },
    tableData: { type: Array, default: () => [] },
    clikcCell: { type: Array, default: () => [] }, // ['market_value', 'delta_pnl', 'account_name']
    showRedGreenColumn: { type: Array, default: () => [] }, // ['market_value', 'delta_pnl']
    showAbsoluteVlue: { type: String, default: '{}' } // 传值格式： '{"market_value":99999999999,"delta_fee":"157950"}'
  }, components: {
    TableColumn
  },
  data() {
    return {
      listLoading: false,
      downloadLoading: false,
      currentPage: 1,
      pagesize: 20,
      absoluteVlue: {},
      deepHead: [],
      head: {},
      value1: [],
      arrs: [],
      options: [],
      mutiOptionsValue: []
    }
  },
  watch: {
    gridTableHeader: {
      deep: true,
      handler() {
        this.iniData()
      }
    },
    mappingName: {
      deep: true,
      handler() {
        this.iniData()
      }
    }
  },
  methods: {
    iniData() {
      this.absoluteVlue = JSON.parse(this.showAbsoluteVlue)
      this.head = this.gridTableHeader
      // console.log('muitable1')
      // console.log(this.gridTableHeader)
      for (const a in this.gridTableHeader) {
        // console.log(Array.isArray(this.gridTableHeader[a]))
        // console.log(this.mappingName)
        if (Array.isArray(this.gridTableHeader[a])) {
          const children = []
          for (const b in this.gridTableHeader[a]) {
            // console.log(this.gridTableHeader[a][b])
            // this.mutiOptionsValue.push(this.gridTableHeader[a][b])
            this.mutiOptionsValue.push([a, this.gridTableHeader[a][b]])
            children.push({
              'value': this.gridTableHeader[a][b],
              'label': this.mappingName[this.gridTableHeader[a][b]]
            })
          }

          this.arrs.push({ 'name': a, 'value': this.gridTableHeader[a], 'lable': this.gridTableHeader[a] })
          this.options.push({
            'value': a,
            'label': a,
            children: children
          })
        }
      }
    },
    selectchange() {
      const tmp = this.copy(this.gridTableHeader)
      for (const a in tmp) {
        if (Array.isArray(tmp[a])) {
          const select = []
          for (const arr in this.mutiOptionsValue) {
            if (a === this.mutiOptionsValue[arr][0]) {
              select.push(this.mutiOptionsValue[arr][1])
            }
          }
          tmp[a] = select
          if (tmp[a].length === 0) {
            delete tmp[a]
          }
        }
      }
      this.head = tmp
    },
    copy(obj) {
      let newObj = null
      if (typeof obj === 'object' && obj !== null) {
        newObj = obj instanceof Array ? [] : {}
        for (const i in obj) {
          newObj[i] = typeof obj[i] === 'object' ? this.copy(obj[i]) : obj[i]
        }
      } else {
        newObj = obj
      }
      return newObj
    },
    headerClassNmae({ row, column, rowIndex, columnIndex }) {
      // // console.log(column)
      if (this.deepHead.indexOf(column.property) >= 0) {
        return 'deepColor'
      }
      return ''
    },
    addClass({ row, column, rowIndex, columnIndex }) {
      // if (this.clikcCell.indexOf(column.property) >= 0) {
      let cls = ''
      if (this.showRedGreenColumn.indexOf(column.property) >= 0) {
        if (row[column.property] > 0) {
          cls = 'red'
        } else {
          cls = 'green'
        }
      }
      if (this.clikcCell.indexOf(column.property) >= 0) {
        cls = cls + ' cellClass'
      }
      if (column.property in this.absoluteVlue) {
        if (Math.abs(row[column.property]) > Math.abs(this.absoluteVlue[column.property])) {
          cls = cls + ' deepBackground'
          if (this.deepHead.indexOf(column.property) < 0) {
            this.deepHead.push(column.property)
          }
          // // console.log(this.deepHead)
        }
      }
      // // console.log(this.absoluteVlue)

      return cls
    },
    handleSizeChange(size) {
      this.pagesize = size
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
    },
    rowclik(row, column, event) {
      // // console.log(row)
      this.$emit('rowClick', row)
    },
    cellDbClick(row, column, cell, event) {
      if (this.clikcCell.indexOf(column.property) >= 0) {
        // this.$message({
        //   message: '该行可以跳转',
        //   type: 'success'
        // })
        this.$emit('cellOnClick', row, column, cell, event)
      }
    },
    /** export table data */
    handleDownload() {
      if (this.tableData.length === 0) {
        [
          this.$notify({
            title: 'error',
            message: 'table is empty'
          })
        ]
        return
      }
      this.downloadLoading = true

      import('@/utils/Export2Excel').then(excel => {
        const tHeader = []
        const filterVal = []

        var jsonHeader = JSON.parse(JSON.stringify(this.gridTableHeader))
        // console.log(jsonHeader)
        // console.log(jsonHeader)
        for (const key in this.gridTableHeader) {
          // console.log(key)
          // console.log(Array.isArray(jsonHeader[key]))
          // console.log(jsonHeader[key])

          if (Array.isArray(jsonHeader[key])) {
            var arr1 = jsonHeader[key]
            for (const item in arr1) {
              // console.log(arr1[item])
              tHeader.push(arr1[item])
              filterVal.push(arr1[item])
            }
          } else {
            tHeader.push(key)
            filterVal.push(key)
          }
        }

        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list' + new Date().getTime()
        })
        this.downloadLoading = false
      })
    },

    formatJson(filterVal) {
      return this.tableData.map(v => filterVal.map(j => {
        return v[j]
      }))
    }

  }
}
</script>

<style>
.cellClass {
  color: blue;
  text-decoration: underline;
}

.red {
  color: red;
}

.deepBackground {
  background: #FEC171 !important;
}

.deepColor {
  color: red;
  background: #FEC171 !important;
}

.green {
  color: green;
}
.el-table .cell {
  white-space: nowrap;
}
.container {
  overflow-x: auto;
}

.feature {
  position: fixed;
  top: 10px;
  right: 10px;
  z-index: 1000;
}

.el-table .cell {
  white-space: nowrap;
}

.copyright {
  text-align: center;
  margin: 100px 20px 20px;
  padding: 20px 0 0;
  border-top: 1px solid #e7e7e7;
}
</style>
